package com.bankcomm.ui.views;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import com.bankcomm.R;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.os.Environment;

/**
 * 学校数据库类
 * 
 * @author zhang.h
 * 
 * @date 2012-7-25 下午06:37:08
 */
public class DBManager {
	public static final int BUFFER_SIZE = 1024;
	public static final String DB_NAME = "university.db"; // 保存的数据库文件名
	public static final String PACKAGE_NAME = "com.bankcomm"; // 包名
	public static final String DB_PATH = "/data"
			+ Environment.getDataDirectory().getAbsolutePath() + "/"
			+ PACKAGE_NAME; // 在手机里存放数据库的位置

	public final static String TABLE_PROVINCE = "PROVINCE";
	public final static String TABLE_PROVINCE_COLUMN_ID = "ID";
	public final static String TABLE_PROVINCE_COLUMN_NAME = "NAME";

	public final static String TABLE_COLLEGE = "COLLEGE";
	public final static String TABLE_COLLEGE_COLUMN_ID = "ID";
	public final static String TABLE_COLLEGE_COLUMN_NAME = "NAME";
	public final static String TABLE_COLLEGE_COLUMN_TYPE = "TYPE";
	public final static String TABLE_COLLEGE_COLUMN_PROVINCE_ID = "PROVINCEID";

	public Context context;

	public DBManager(Context context) {
		this.context = context;
	}

	public SQLiteDatabase openDatabase() {
		String dbfile = DB_PATH + "/" + DB_NAME;
		// 判断数据库文件是否存在, 若不存在则执行导入, 否则直接打开数据库
		try {
			if (!new File(dbfile).exists()) {
				// 欲导入的数据库
				InputStream is = context.getResources().openRawResource(
						R.raw.university);
				FileOutputStream fos = new FileOutputStream(dbfile);
				byte[] buffer = new byte[BUFFER_SIZE];
				int count = 0;
				while ((count = is.read(buffer)) > 0) {
					fos.write(buffer, 0, count);
				}
				fos.close();
				is.close();
			}
			SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(dbfile,
					null);
			return db;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
}
